package com.stn.zjx.givingtreasure.application;

import android.app.Application;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.multidex.MultiDex;
import android.support.multidex.MultiDexApplication;
import android.widget.Toast;



import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheEntity;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.cookie.CookieJarImpl;
import com.lzy.okgo.cookie.store.DBCookieStore;
import com.lzy.okgo.https.HttpsUtils;
import com.lzy.okgo.interceptor.HttpLoggingInterceptor;
import com.lzy.okgo.model.HttpHeaders;
import com.lzy.okgo.model.HttpParams;
import com.mob.MobSDK;
import com.orhanobut.logger.AndroidLogAdapter;
import com.orhanobut.logger.Logger;
import com.sina.weibo.sdk.WbSdk;
import com.sina.weibo.sdk.auth.AuthInfo;
import com.stn.zjx.givingtreasure.constants.StnConstants;
import com.stn.zjx.givingtreasure.database.GreenDaoManager;
import com.stn.zjx.givingtreasure.net.BaseApi;
import com.stn.zjx.givingtreasure.service.AdvanceLoadX5Service;
import com.stn.zjx.givingtreasure.utils.ToolsUtils;


import com.tencent.bugly.crashreport.CrashReport;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.smtt.sdk.QbSdk;
import com.tencent.tauth.Tencent;
import com.vondear.rxtools.RxTool;



import java.util.concurrent.TimeUnit;
import java.util.logging.Level;

import cn.bingoogolapple.swipebacklayout.BGASwipeBackHelper;
import cn.jpush.android.api.JPushInterface;
import okhttp3.OkHttpClient;

public class StnApp extends MultiDexApplication {
    public static IWXAPI iwxapi;
    public static Tencent tencent;

    public static StnApp getApplication() {
        return application;
    }

    public static void setApplication(StnApp application) {
        StnApp.application = application;
    }

    private static StnApp application;

    @Override
    public void onCreate() {
        super.onCreate();
        application=this;
        // Fresco图片

        JPushInterface.setDebugMode(true);
        JPushInterface.init(this);
        //通用工具
        RxTool.init(getApplicationContext());
        //网络框架
        initOkgo();
        //初始化数据库
        setupDatabase();
        //日志
        initLogger();
        //手滑返回
        BGASwipeBackHelper.init(this, null);
        //xwebview
        preinitX5WebCore();
        Intent intent = new Intent(this, AdvanceLoadX5Service.class);
        startService(intent);
        WbSdk.install(this,new AuthInfo(this, StnConstants.sina_key, StnConstants.REDIRECT_URL, StnConstants.SCOPE));
        MobSDK.init(this);
        //初始化腾讯
        tencent = Tencent.createInstance(StnConstants.qq_id,this);
        //初始化微信
        iwxapi= WXAPIFactory.createWXAPI(this, StnConstants.wx_key, true);
        iwxapi.registerApp(StnConstants.wx_key);

        //初始化异常上报
        initCashReport();


    }
    private void preinitX5WebCore() {
        if (!QbSdk.isTbsCoreInited()) {
            QbSdk.preInit(getApplicationContext(), null);// 设置X5初始化完成的回调接口
        }
    }
    /**
     * 初始化OKGO网络框架
     */
    private void initOkgo(){
        //客户端配置创建
        OkHttpClient.Builder builder =new  OkHttpClient.Builder();
        //设置网络请求打印日志
        HttpLoggingInterceptor loggingInterceptor =new HttpLoggingInterceptor("OkGo");
        //log打印级别，决定了log显示的详细程度
        loggingInterceptor.setPrintLevel(HttpLoggingInterceptor.Level.BODY);
        //log颜色级别，决定了log在控制台显示的颜色
        loggingInterceptor.setColorLevel(Level.INFO);
        builder.addInterceptor(loggingInterceptor);
        //全局的读取超时时间
        builder.readTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);
        //全局的写入超时时间
        builder.writeTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);
        //全局的连接超时时间
        builder.connectTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);
        //使用sp保持cookie，如果cookie不过期，则一直有效
//        builder.cookieJar(CookieJarImpl(SPCookieStore(this)))
        //使用数据库保持cookie，如果cookie不过期，则一直有效
        builder.cookieJar(new CookieJarImpl(new DBCookieStore(this)));
        //使用内存保持cookie，app退出后，cookie消失
        //      builder.cookieJar(CookieJarImpl(MemoryCookieStore()))
        //方法一：信任所有证书,不安全有风险
        HttpsUtils.SSLParams sslParams1 = HttpsUtils.getSslSocketFactory();

        //方法二：自定义信任规则，校验服务端证书
        //   SSLParams sslParams2 = HttpsUtils.getSslSocketFactory(new SafeTrustManager());
//方法三：使用预埋证书，校验服务端证书（自签名证书）
        //  SSLParams sslParams3 = HttpsUtils.getSslSocketFactory(getAssets().open("srca.cer"));
//方法四：使用bks证书和密码管理客户端证书（双向认证），使用预埋证书，校验服务端证书（自签名证书）
        //SSLParams sslParams4 = HttpsUtils.getSslSocketFactory(getAssets().open("xxx.bks"), "123456", getAssets().open("yyy.cer"));
        builder.sslSocketFactory(sslParams1.sSLSocketFactory, sslParams1.trustManager);
//配置https的域名匹配规则，详细看demo的初始化介绍，不需要就不要加入，使用不当会导致https握手失败
        //builder.hostnameVerifier(new SafeHostnameVerifier());
        //---------这里给出的是示例代码,告诉你可以这么传,实际使用的时候,根据需要传,不需要就不传-------------//
        HttpHeaders headers = new HttpHeaders();
//        headers.put("commonHeaderKey1", "commonHeaderValue1")    //header不支持中文，不允许有特殊字符
//        headers.put("commonHeaderKey2", "commonHeaderValue2")
        HttpParams params =new HttpParams();
        params.put(BaseApi.KEY_Client_CommonParams, ToolsUtils.getCommonParams());
//        params.put("commonParamsKey1", "commonParamsValue1")     //param支持中文,直接传,不要自己编码
//        params.put("commonParamsKey2", "这里支持中文参数")
        OkGo.getInstance().init(this)                       //必须调用初始化
                .setOkHttpClient(builder.build())               //建议设置OkHttpClient，不设置将使用默认的
                .setCacheMode(CacheMode.NO_CACHE)               //全局统一缓存模式，默认不使用缓存，可以不传
                .setCacheTime(CacheEntity.CACHE_NEVER_EXPIRE)   //全局统一缓存时间，默认永不过期，可以不传
                .setRetryCount(3)                               //全局统一超时重连次数，默认为三次，那么最差的情况会请求4次(一次原始请求，三次重连请求)，不需要可以设置为0
                .addCommonHeaders(headers)                      //全局公共头
                .addCommonParams(params);

    }

    /**
     * 初始化数据库
     */
    private void  setupDatabase(){
        GreenDaoManager.getInstance().init(this);
    }

    /**
     * 初始化Logger日志工具
     */
    private void initLogger(){
        Logger.addLogAdapter(new AndroidLogAdapter());
    }


     private void initCashReport(){

         Context context = getApplicationContext();
// 获取当前包名
         String packageName = context.getPackageName();
// 获取当前进程名
         String processName = ToolsUtils.getProcessName(android.os.Process.myPid());
// 设置是否为上报进程
         CrashReport.UserStrategy strategy = new CrashReport.UserStrategy(context);
         strategy.setUploadProcess(processName == null || processName.equals(packageName));
// 初始化Bugly
      CrashReport.initCrashReport(getApplicationContext(), StnConstants.bugly_id, true,strategy);


     }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }
}
